import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/custom/noData.dart';
import 'package:flutter_juwo/ui/custom/select_pic_widget.dart';
import 'package:flutter_juwo/ui/pages/photoHero/PhotoHero.dart';
import 'package:flutter_juwo/ui/utils/select_pic.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'model/submit_entity.dart';
import 'model/type_entity.dart';
import 'model/up_image_entity.dart';

import 'package:flutter/scheduler.dart' show timeDilation;

import '../../photoHero/showBigImage.dart';

class AddRepresentation extends StatefulWidget {
  @override
  _AddRepresentationState createState() => _AddRepresentationState();
}

class _AddRepresentationState extends State<AddRepresentation> {
  MyPageState ps = MyPageState.LOADING;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  TypeEntity typeEntity = null;
  String typeName = ""; //申述类型
  String typeId = "";
  List<String> typeList = [];
  TextEditingController _textEditingController = TextEditingController();
  int picNum = 3; //故障图片最多四张

  ///图片
  List<File> images = [];
  List<String> imgUrls = [];

  ///服务器返回地址

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    timeDilation = 2.0; // 1.0 means normal animation speed.

    return Scaffold(
      key: _scaffoldKey,
      appBar: UiUtils.appBar(context, "我要申诉"),
      body: getBody(),
    );
  }

  void getData() {
    DioManager.getInstance().get(Api.USER_APPLYTYPE, null, (json) {
      print("获取申诉类型：$json");
      typeEntity = TypeEntity.fromJson(json);

      if (null == typeEntity) {
        ps = MyPageState.NOT_DATA;
        return;
      }

      if (typeEntity.status != 200) {
        ToastUtil.showShortErrToast(typeEntity.message);
        NavigatorUtils.goBackWithParams(context, false);
        return;
      }

      ps = MyPageState.HAVE_DATA;
      for (int i = 0; i < typeEntity.data.length; i++) {
        typeList.add(typeEntity.data[i].name);
      }
      setState(() {});
    }, (err) {
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
      NavigatorUtils.goBackWithParams(context, false);
    });
  }

  getBody() {
    if (ps == MyPageState.HAVE_DATA) {
      return this.getContent();
    }

    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.NOT_DATA) {
      return NoData(getData);
    }
  }

  getContent() {
    return ListView(
      children: <Widget>[
        UiUtils.divider(),
        this.getRow1(),
        this.getRow2(),
        this.getRow3(),
        this.getRow4(),
      ],
    );
  }

  getRow4() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(60), ScreenUtil().setWidth(30), 0),
      child: UiUtils.bottomBotton("提交", () {
        if (!checkData()) {
          return;
        }
        showMyDialog();

        ///提交
        this.upDate();
      }),
    );
  }

  showPicker(BuildContext context) {

    List<Widget> widgets = [];
    widgets.add(
      Container(
        height: ScreenUtil().setWidth(78),
        child: Text(
          "选择申诉类型",
          style:
          TextStyles.custom(30, Colours.appC1, Font.PingFangBlod),
        ),
      ),
    );
    for (int i = 0; i < typeList.length; i++) {
      widgets.add(UiUtils.divider());
      widgets.add(InkWell(
        onTap: () {
          typeName = typeList[i];
          typeId = typeEntity.data[i].id;
          setState(() {});
          NavigatorUtils.goBack(context);
        },
        child: Container(
          height: ScreenUtil().setWidth(90),
          alignment: Alignment.center,
          child: Text(
            "${typeList[i]}",
            style: TextStyles.custom(
                28, Colours.appC16, Font.PingFangMedium),
          ),
        ),
      ));
    }

    showElasticDialog(
        context: context,
        builder: (BuildContext context) {
          return Material(
            type: MaterialType.transparency,
            child: Center(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.0),
                ),
                width: ScreenUtil().setWidth(540),
                height: ScreenUtil()
                    .setWidth(48 + 78 + (90 + 1.0) * typeList.length),
                padding: EdgeInsets.only(top: ScreenUtil().setWidth(48)),
                child: Theme(
                  data: ThemeData(
                    buttonTheme: ButtonThemeData(
                      minWidth: double.infinity,
                    ),
                    textTheme: TextTheme(
                        button: TextStyle(
                          fontSize: Dimens.font_sp14,
                        )),
                  ),
                  child: Column(
                    children: widgets,
                  ),
                ),
              ),
            ),
          );
        });
  }

  getRow1() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30)),
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(2)),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(right: ScreenUtil().setWidth(80)),
            child: Text(
              "申诉类型",
              style: TextStyles.custom(
                  30, Colours.appC1, Font.PingFangMedium),
            ),
          ),
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                showPicker(context);
              },
              child: Text(
                typeName == "" ? "请选择" : typeName,
                textAlign: TextAlign.end,
                style: TextStyles.custom(
                    28, Colours.appC3, Font.PingFangMedium),
              ),
            ),
          )
        ],
      ),
    );
  }

  getRow2() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), 0),
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(2)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(right: ScreenUtil().setWidth(80)),
            child: Text(
              "申诉内容",
              style: TextStyles.custom(
                  30, Colours.appC1, Font.PingFangMedium),
            ),
          ),
          Container(
            margin: EdgeInsets.only(
                top: ScreenUtil().setWidth(30),
                bottom: ScreenUtil().setWidth(30)),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6), color: Colours.c243),
            child:  UiUtils.myTextField(context, _textEditingController, hintText: "", maxLines: 6)/*TextField(
              controller: _textEditingController,
              maxLines: 5,
              decoration: InputDecoration(border: InputBorder.none),
            )*/,
          )
        ],
      ),
    );
  }

  getRow3() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), 0),
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(2)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: ScreenUtil().setWidth(30)),
            child: Text(
              "问题截图",
              style: TextStyles.custom(
                  30, Colours.appC1, Font.PingFangMedium),
            ),
          ),
          SelectPicWidget(picNum,(List<String> values){
            imgUrls=values;
          }),

        ],
      ),
    );
  }



  Future upDate() async {
    String imagesJson = this.getImagesJson();
    var deviceInfor = await getDeviceInfor();

    FormData formData = FormData.from({
      "phone": deviceInfor,
      "problem_type": typeId,
      "images": imagesJson,
      "problem": _textEditingController.text
    });

    DioManager.getInstance().post(Api.USER_ADDAPPLY, formData, (json) {
      SubmitEntity entity = SubmitEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }

      if (entity.code != 200) {
        ToastUtil.showShortErrToast(entity.message);
        NavigatorUtils.goBack(context);
        return;
      }
      ToastUtil.showShortToast("已提交！");
      NavigatorUtils.goBack(context);
      NavigatorUtils.goBackWithParams(context, true);
      return;
    }, (err) {
      ToastUtil.showShortErrToast(err);
      NavigatorUtils.goBack(context);
    });
  }

  Future<String> getDeviceInfor() async {
    DeviceInfoPlugin deviceInfo = new DeviceInfoPlugin();
    if (Platform.isIOS) {
      IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
      print("iosDeviceInfo:${iosDeviceInfo.toString()}");
      return "IosOS--- ${iosDeviceInfo.model}";
    } else if (Platform.isAndroid) {
      AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
      return "AndroidOS--- ${androidDeviceInfo.model}";
    }
  }

  String getImagesJson() {
    ///[{"img":"http://154.91.3.148:8083/uploads/images/201910/app_apply201910101445268395377file.png"},{"img":"http://154.91.3.148:8083/uploads/images/201910/app_apply201910101445268395377file.png"}]

    StringBuffer sb = new StringBuffer();
    sb.write("[");
    for (int i = 0; i <= imgUrls.length - 1; i++) {
      sb.write("{\"img\":\"");
      sb.write(imgUrls[i]);
      sb.write("\"}");
      if (i != imgUrls.length - 1) {
        sb.write(",");
      }
    }
    sb.write("]");
    return sb.toString();
  }

  bool checkData() {
    if (typeId.isEmpty) {
      ToastUtil.showShortErrToast("请选择申请类型！");
      return false;
    }

    if (_textEditingController.text.isEmpty) {
      ToastUtil.showShortErrToast("请输入申诉内容！");
      return false;
    }

    if (imgUrls.length <= 0) {
      ToastUtil.showShortErrToast("请上传申诉截图！");
      return false;
    }
    return true;
  }

  void showMyDialog() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return LoadingDialog(
            text: "正在提交",
          );
        });
  }
}
